import java.io.*;
import java.util.*;

public class FileSE implements SEServer.SearchService {
	
	//I will create a hashtable that stores each word as a key, and the lines it appears in in a hashset as the value. 
	private Hashtable<String,HashSet<Integer>> table = new Hashtable<String,HashSet<Integer>>(); 
	private int linecount=0;
	
    private ArrayList<String> lines = new ArrayList<String>();

    public FileSE(String fileName) throws IOException {
        // Opens a file and creates a "reader" handle for it...
        BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));

        // ... which can then be used to read one line at a time:
        while (true) {
            String s = r.readLine();
            if (s == null) break; // no more lines
            for (String word:s.split("\\W+")){
                HashSet<Integer> set = table.get(word.toLowerCase());
                if(set ==null) set = new HashSet<Integer>();
                set.add(linecount);
            	table.put(word.toLowerCase(),set);            	
            }
            linecount++;

        }
    }

    public Iterable<String> search(String queryString) {
    	queryString =queryString.toLowerCase();
        ArrayList<String> r = new ArrayList<String>();
        ArrayList<Integer> list = new ArrayList<Integer>();
        
        ArrayList<Integer> toDelete = new ArrayList<Integer>();
        
        for (String word:queryString.split("\\W+")){
        	if(table.get(word)==null) {list.clear(); break;}        	
        	else{
        		if(list.isEmpty()){
        			list.addAll(table.get(word));
        		}
        		else{
		        	for (Integer i:list){
		        		if(!table.get(word).contains(i)){
		        				toDelete.add(i);
		        		}
		        	}
		        	list.removeAll(toDelete);
		        	toDelete.clear();
        		}
        	}
        }
        if(list.isEmpty()) r.add("No search hits!");
        	else{r.add(list.toString());}
        return r;
    }

    public static void main(String[] args) throws IOException {
        if (args.length != 1) {
            System.err.println("Please give a single file name as argument.");
            System.exit(2);
        }
        String fileName = args[0];

        FileSE engine = new FileSE(fileName);
        SEServer server = new SEServer(8888, engine);
        server.run();
    }
}